//
//  GalleryViewController.m
//  RtspClient
//
//  Created by qi tan on 2024/1/4.
//  Copyright © 2024 Andres Rojas. All rights reserved.
//

#import "GalleryViewController.h"
#import "VideoCell.h"
#import <AssetsLibrary/AssetsLibrary.h> // 必须导入
#import <Photos/Photos.h>

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h> // ios9,视频播放
// 9中播放视频，需要的框架。

// 视频URL路径
#define KOriginalPhotoImagePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]
// 视频URL路径
#define KVideoUrlPath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"VideoURL"]
// caches路径
#define KCachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]


@interface GalleryViewController () <UITableViewDataSource, UITableViewDelegate >
// tab切换组件
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;
@property (weak, nonatomic) IBOutlet UIView *view00;
@property (weak, nonatomic) IBOutlet UIView *view01;
/* 当前tab */
@property (nonatomic, assign) int currentTabIndex;

// 视频列表，图片列表展示。
@property (weak, nonatomic) IBOutlet UITableView *tableView00;
@property (weak, nonatomic) IBOutlet UITableView *tableView01;
// 数据源
@property(nonatomic, strong) NSMutableArray *videos; // 视频列表
@property(nonatomic, strong) NSMutableArray *images; // 截图列表


@property (weak, nonatomic)  UIButton *btnCover;

@property (strong,nonatomic)AVPlayer *player;

// 临时
@property (nonatomic,strong) NSMutableArray    *groupArrays;
// 强引用属性，无view的视频播放器。
@property (nonatomic,strong) MPMoviePlayerController *mpc;
@end

@implementation GalleryViewController
#pragma mark 懒加载数据

- (void)initDataList {
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    NSArray *subPaths = [fmgr subpathsAtPath:docPath]; // 获取文件列表
    NSLog(@"--------------");
    for (NSString *fileName in subPaths) {
        NSLog(@"排序前 %@", fileName);
    }
    NSLog(@"-------开始排序: 倒序显示所有文件-------");
    NSArray *sorted = [subPaths sortedArrayUsingComparator:^NSComparisonResult(NSString *firstPath,NSString *secondPath) {
        NSString *firstUrl = [docPath stringByAppendingPathComponent:firstPath];
        NSString *secondUrl = [docPath stringByAppendingPathComponent:secondPath];
        
        NSDictionary *firstFileInfo = [[NSFileManager defaultManager]
                                       attributesOfItemAtPath:firstUrl error:nil];
        NSDictionary *secondFileInfo = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:secondUrl error:nil];
        id firstData = [firstFileInfo objectForKey:NSFileCreationDate];
        id secondData = [secondFileInfo objectForKey:NSFileCreationDate];
        return [secondData compare:firstData];
    }];
    
    // 分别处理视频列表数据，图片列表数据
    NSMutableArray * array00 = [NSMutableArray array];
    NSMutableArray * array01 = [NSMutableArray array];
    for (NSString *fileName2 in sorted) {
        if([fileName2 hasSuffix:@".mp4"]) { // 视频
            [array00 addObject: fileName2];
        } else if([fileName2 hasSuffix:@".png"]) { // 图片
            [array01 addObject:fileName2];
        }
    }
    _videos = array00;
    _images = array01;
    
    [self initTempDirVideos];
    for (NSString *videoFile in array00) {
        NSLog(@"视频文件---- %@", videoFile);
    }
}

// 处理TempDir的视频。
-(void)initTempDirVideos {
    NSString * tmpDir = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 获取目录下的所有文件名数组
    NSError *error;
    NSArray *subPaths = [fileManager contentsOfDirectoryAtPath:tmpDir error:&error];
    
    NSArray *sorted = [subPaths sortedArrayUsingComparator:^NSComparisonResult(NSString *firstPath,NSString *secondPath) {
        NSString *firstUrl = [tmpDir stringByAppendingPathComponent:firstPath];
        NSString *secondUrl = [tmpDir stringByAppendingPathComponent:secondPath];
        
        NSDictionary *firstFileInfo = [[NSFileManager defaultManager]
                                       attributesOfItemAtPath:firstUrl error:nil];
        NSDictionary *secondFileInfo = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:secondUrl error:nil];
        id firstData = [firstFileInfo objectForKey:NSFileCreationDate];
        id secondData = [secondFileInfo objectForKey:NSFileCreationDate];
        return [secondData compare:firstData];
    }];
    NSMutableArray * array00 = [NSMutableArray array];
    for (NSString *fileName2 in sorted) {
        if([fileName2 hasSuffix:@".mp4"]) { // 视频
            [array00 addObject: fileName2];
        }
    }
    _videos = array00;
}



#pragma mark 界面初始化，数据源代理设置。
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle: NSLocalizedString(@"gallery", nil)];
    
    [self initDataList]; // 初始化数据
    self.tableView00.dataSource = self;
    self.tableView01.dataSource = self;
    self.tableView00.delegate = self;
    self.tableView01.delegate = self;
    self.tableView00.rowHeight = 94;
    self.tableView01.rowHeight = 94;
    
    
    self.currentTabIndex = 0;
    self.view01.hidden = YES;
    // 监听顶部tab点击事件
    [self.segmentControl addTarget:self action:@selector(selectItem:) forControlEvents:UIControlEventValueChanged];
    
    // 相册文件1，导出到沙盒中。TODO
    // 相册视频2，导出到沙盒中。TODO
    self.groupArrays = [NSMutableArray array];
}


#pragma mark 顶部tab点击切换
- (void)selectItem:(UISegmentedControl *)sender {
    if(sender.selectedSegmentIndex == 0) {
        NSLog(@"tab1 selected");
        self.view00.hidden = NO;
        self.view01.hidden = YES;
        self.currentTabIndex = 0;
        [self.tableView00 reloadData]; // 刷新列表数据
    } else {
        self.currentTabIndex = 1;
        NSLog(@"tab2 selected");
        self.view00.hidden = YES;
        self.view01.hidden = NO;
        [self.tableView01 reloadData];
    }
}

#pragma mark 列表侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除item操作。
        [self showDeleteDialog:tableView withIndexPath: indexPath];
    }
}
// TODO 无效方法 delete
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:( NSIndexPath *)indexPath{
    return NSLocalizedString(@"delete", nil);
}

// 二次弹框，确认删除 sure_to_delete
- (void)showDeleteDialog:(UITableView *)tableView withIndexPath:(NSIndexPath *) indexPath {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"prompt", nil)
        message:NSLocalizedString(@"sure_to_delete", nil)
        preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil)
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"confirm", nil)
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"row: %zd", indexPath.row);
            if(self.currentTabIndex == 0) {
                [self deleteTempDirFile:self.videos[indexPath.row]]; // 先删除原始集合中数据
                [self.videos removeObjectAtIndex:indexPath.row];
            } else {
                [self deleteShaHeFile:self.images[indexPath.row]];
                [self.images removeObjectAtIndex:indexPath.row];
            }
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 删除临时文件夹中的视频文件
-(void)deleteTempDirFile:(NSString *)fileName{
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    BOOL result = [fmgr removeItemAtPath:filePath error:nil];
    if(result){
        NSLog(@"删除视频元素: %@", fileName);
    } else {
        NSLog(@"删除视频失败: %@", fileName);
    }
}

// 删除图片
- (void)deleteShaHeFile:(NSString *)fileName {
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    NSString *fileUrl = [docPath stringByAppendingPathComponent:fileName];
    BOOL result = [fmgr removeItemAtPath:fileUrl error:nil];
    if(result){
        NSLog(@"删除元素: %@", fileName);
    } else {
        NSLog(@"删除失败: %@", fileName);
    }
}







#pragma mark 列表数据源方法。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.currentTabIndex == 0) {
        return self.videos.count;
    }
    return self.images.count;
}
// 列表item的显示样式。bug
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 1.获取模型数据
    NSString *model = nil;
    VideoCell *cell = nil;
    if(self.currentTabIndex == 0) { // 视频tab
        if(indexPath.row < self.videos.count) {
            model = self.videos[indexPath.row];
            cell = [VideoCell videoImageCellWithTableView:self.tableView00];
        }
    } else { // 图片tab
        if(indexPath.row < self.images.count){
            model = self.images[indexPath.row];
            cell = [VideoCell videoImageCellWithTableView:self.tableView01];
        }
    }
    // 使用xib方式，创建自定义view
    cell.item = model;
    return cell;
}

#pragma mark 列表cell选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(self.currentTabIndex == 0) {
        NSString * fileName = self.videos[indexPath.row];
        NSLog(@"选择ship: %@", fileName);
        // 点击视频item 后，进入视频播放界面。
        NSString *path =[NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        NSURL *nsUrl = [NSURL fileURLWithPath:path];
        [self playVideo9WithNSURL:nsUrl];
    } else {
        NSString * name = self.images[indexPath.row];
        NSLog(@"选择image: %@", name);
        [self showImageFullScreen:name];;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


// iOS9 版本的视频播放。AVPlayer
-(void)playVideo9WithNSURL: (NSURL*) url{
    AVPlayerViewController *pvc = [AVPlayerViewController new];
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"7_1708680983.mp4" withExtension:nil];
    pvc.player = [AVPlayer playerWithURL:url];
    [pvc.player play]; // 开始播放
    
    // 模态弹出, 模态弹出要等view显示之后。应该在视图出现之后，调用。
    [self presentViewController:pvc animated:YES completion:nil];
    // 如果要自定义播放器的大小，应该自定义，设置frame，添加到视图中。
}


// 全屏显示图片
- (void)showImageFullScreen:(NSString *)fileName {
    UIButton *btnCover = [[UIButton alloc] init];
    btnCover.frame = self.view.frame;
    btnCover.backgroundColor = [UIColor blackColor];
    btnCover.alpha = 0.0;
    [self.view addSubview:btnCover];
    self.btnCover = btnCover;
    // 阴影添加点击事件
    [btnCover addTarget:self action:@selector(smallImage) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:fileName];
    // 把模型的数据，设置给子控件。
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    UIImageView *bigImage = [[UIImageView alloc] initWithImage:image];
    bigImage.frame = CGRectZero;
    [btnCover addSubview: bigImage];
    
    CGFloat iconW = self.view.bounds.size.width;
    CGFloat iconH = 0.75 * iconW;
    CGFloat iconX= 0;
    CGFloat iconY = (self.view.bounds.size.height - iconH) * 0.5;
    
    [UIView animateWithDuration:0.5 animations:^{
            btnCover.alpha = 1;
            bigImage.frame = CGRectMake(iconX, iconY, iconW, iconH);
        }];
}

- (void)smallImage {
    // 大图变小。移除。
    NSLog(@"smallImage");
    [self.btnCover removeFromSuperview];
    self.btnCover = nil;
}

#pragma mark 拷贝代码中的视频文件，到临时文件夹中。
-(void)expertVideoToTempDir {
    // In视频源文件, 压缩处理。
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"workspace.mp4" withExtension:nil];
    AVAsset *asset = [AVAsset assetWithURL:url];
    //2.presetName压缩大小
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset
                                                                    presetName:AVAssetExportPresetLowQuality];
    // 3.设置导出路径, 临时主目录
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePathDest = [docPath stringByAppendingPathComponent:@"Tomcat.mp4"];
    NSString *tempDirFilePath =[NSTemporaryDirectory()
                                stringByAppendingPathComponent:@"2320.mp4"];
    
    session.outputURL = [NSURL fileURLWithPath:tempDirFilePath];
    // 4.设置导出类型
    session.outputFileType = AVFileTypeQuickTimeMovie;
    // 5. 开始导出
    [session exportAsynchronouslyWithCompletionHandler:^{
        NSLog(@"导出已经成功了");
    }];
}

// 检测临时目录，是否有视频
-(void) checkTempDirVideo {
    NSString * tmpDir = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 获取目录下的所有文件名数组
   NSError *error;
   NSArray *filesInDirectory = [fileManager contentsOfDirectoryAtPath:tmpDir error:&error];
   if (error) {
       NSLog(@"Error getting files in directory: %@", error);
   } else {
       for (NSString *fileName in filesInDirectory) {
           NSLog(@"%@", fileName);
           
           if([fileName isEqualToString:@"2320.mp4"]) {
               NSString *path =[NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
               NSURL * url = [NSURL fileURLWithPath:path];
               [self playVideo9WithNSURL:url];
           }
       }
   }
}


@end

